package com.rzico.sbl.ui.member

import android.view.View
import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberBillBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.GoodsData
import com.rzico.sbl.ui.goods.GoodsActivity
import com.rzico.sbl.viewmodel.MemberViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class MemberBillActivity : BaseActivity(R.layout.activity_member_bill) {

    private val mBinding by lazy { ActivityMemberBillBinding.bind(getRootView()) }

    private var mCardId = ""
    private var isEditMode = false

    override fun getViewModel() = get<MemberViewModel>()

    override fun initData() {
        initTitle(title = "记账商品", name = "编辑")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData()
    }

    private fun initLayout() {
        mBinding.apply {
            billAll.setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

            listLayout.apply {
                emptyLayout.also {
                    it.emptyHint.text = "未选择指定商品时默认可全部记账！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData() }
                    )

                    layout.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<GoodsData>(R.layout.item_goods_list) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_goods_name, bean.name)
                                text(R.id.item_goods_price, bean.price.formatDecimal())
                                text(
                                    R.id.item_goods_tag,
                                    bean.tags.joinToString("、") { it.name }
                                )

                                getView<View>(R.id.item_goods_tag).isVisible =
                                    bean.tags.isNotEmpty()
                                getView<View>(R.id.item_goods_has).isVisible =
                                    bean.availableStock.intValue == 0

                                with<ImageView>(R.id.item_goods_logo) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<TextView>(R.id.item_goods_stock) {
                                    it.text = bean.availableStock
                                    it.setTextColor(
                                        getColorEx(
                                            conditionIf(
                                                bean.availableStock.intValue < 100,
                                                R.color.red,
                                                R.color.gray
                                            )
                                        )
                                    )
                                }

                                with<ImageView>(R.id.item_goods_check) {
                                    it.isVisible = isEditMode
                                    it.setImageResource(
                                        conditionIf(
                                            bean.check,
                                            R.mipmap.login_yes_orange,
                                            R.mipmap.login_no
                                        )
                                    )
                                }

                                clicked {
                                    isEditMode
                                        .condition {
                                            bean.check = !bean.check
                                            notifyItemChanged(index)

                                            checkTextHint()
                                        }
                                }

                                longClicked {
                                    isEditMode.conditionFalse {
                                        deleteGoods(bean.productId, index)
                                    }

                                    true
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }

            tvRight?.oneClick { view ->
                view as TextView
                isEditMode = !isEditMode

                isEditMode
                    .apply {
                        view.text = conditionIf(this, "取消", "编辑")
                        billEdit.isInvisible = !this
                        btAdd.isGone = this
                    }
                    .condition {
                        mList.forEach {
                            it as GoodsData
                            it.check = false
                        }

                        checkTextHint()
                    }

                mAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initListener() {
        mCardId = intent.getExtra("cardId")

        mBinding.apply {
            btDel.oneClick {
                mList.none { (it as GoodsData).check }
                    .condition {
                        showToast("请选择要删除的商品")
                        return@oneClick
                    }

                getViewModel()
                    .requestBind(
                        requestUrl = BaseUrl.billDel,
                        params = arrayOf(
                            "id" to mCardId,
                            "productIds" to mList
                                .filter { (it as GoodsData).check }
                                .joinToString(",") { (it as GoodsData).productId }
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("删除商品成功！")

                            isEditMode = false
                            tvRight?.text = "编辑"
                            billEdit.isInvisible = !isEditMode
                            btAdd.isGone = isEditMode

                            updateList()
                        }
                    )
            }

            btAdd.oneClick {
                startActivityEx<GoodsActivity>(
                    "mode" to "multiple",
                    "hint" to "请选择要记账的商品",
                    "productIds" to mList.joinToString(",") { (it as GoodsData).productId }
                )
            }
        }

        observe<String>("goodsMultiple") {
            getViewModel().delay {
                getViewModel()
                    .requestBind(
                        requestUrl = BaseUrl.billAdd,
                        params = arrayOf(
                            "id" to mCardId,
                            "productIds" to it
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("添加商品成功！")

                            updateList()
                        }
                    )
            }
        }
    }

    private fun checkTextHint() {
        mBinding.apply {
            billAll.apply {
                setOnCheckedChangeListener(null)
                isChecked =
                    mList.isNotEmpty() && mList.none { !(it as GoodsData).check }
                setOnCheckedChangeListener(this@MemberBillActivity)
            }

            btDel.text = "删除 (${mList.count { (it as GoodsData).check }})"
        }
    }

    /**
     * 删除记账商品
     */
    private fun deleteGoods(itemId: String, index: Int) {
        showHintDialog(
            title = "删除商品",
            hint = "确定要删除商品吗？",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.billDel,
                        params = arrayOf(
                            "id" to mCardId,
                            "productIds" to itemId
                        ),
                        onSuccess = {
                            showToast("商品删除成功！")

                            mList.removeAt(index)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }

                            mBinding
                                .listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 记账商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .billList(
                cardId = intent.getExtra("cardId"),
                onSuccess = {
                    mList.apply {
                        clear()
                        addItems(it)
                    }

                    mAdapter.setDataList(mList)

                    isEditMode
                        .condition {
                            checkTextHint()
                        }
                },
                onFinally = {
                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as GoodsData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        checkTextHint()
    }

}